package com.bookstore.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookstore.back.entity.BookReview;
import com.bookstore.back.entity.Book;
import com.bookstore.back.entity.User;
import com.bookstore.back.entity.ReviewLike;
import com.bookstore.back.mapper.BookReviewMapper;
import com.bookstore.back.mapper.ReviewLikeMapper;
import com.bookstore.back.service.ReviewService;
import com.bookstore.back.service.BookService;
import com.bookstore.back.service.UserService;
import com.bookstore.back.vo.ReviewVO;
import com.bookstore.back.util.UserContextUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 图书评论服务实现类
 *
 * @author 程序猿_Ti
 * @since 2025-07-19
 */
@Slf4j
@Service
public class ReviewServiceImpl extends ServiceImpl<BookReviewMapper, BookReview> implements ReviewService {

    @Autowired
    private BookService bookService;

    @Autowired
    private UserService userService;

    @Autowired
    private ReviewLikeMapper reviewLikeMapper;

    @Autowired
    private UserContextUtil userContextUtil;

    /**
     * 重写save方法，添加评论时同时更新书籍的评论数
     */
    @Override
    @Transactional
    public boolean save(BookReview entity) {
        // 保存评论
        boolean result = super.save(entity);

        if (result && entity.getBookId() != null) {
            // 更新书籍的评论数
            updateBookReviewCount(entity.getBookId());
        }

        return result;
    }

    /**
     * 重写removeById方法，删除评论时同时更新书籍的评论数
     */
    @Override
    @Transactional
    public boolean removeById(Serializable reviewId) {
        // 先获取评论信息
        BookReview review = this.getById(reviewId);

        // 删除评论
        boolean result = super.removeById(reviewId);

        if (result && review != null && review.getBookId() != null) {
            // 更新书籍的评论数
            updateBookReviewCount(review.getBookId());
        }

        return result;
    }

    /**
     * 更新书籍的评论数
     */
    private void updateBookReviewCount(Integer bookId) {
        try {
            // 统计该书籍的评论数（只统计状态为1的评论）
            QueryWrapper<BookReview> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("book_id", bookId);
            queryWrapper.eq("status", 1);
            long reviewCount = this.count(queryWrapper);

            // 更新书籍表的评论数
            Book book = new Book();
            book.setId(bookId);
            book.setReviewCount((int) reviewCount);
            bookService.updateById(book);
        } catch (Exception e) {
            // 记录日志但不影响主流程
            e.printStackTrace();
        }
    }

    @Override
    public IPage<ReviewVO> getReviewList(Map<String, Object> params) {
        // 分页参数
        int current = Integer.parseInt(params.getOrDefault("current", "1").toString());
        int size = Integer.parseInt(params.getOrDefault("size", "10").toString());

        // 查询条件
        QueryWrapper<BookReview> queryWrapper = new QueryWrapper<>();

        // 图书ID筛选
        String bookIdStr = (String) params.get("bookId");
        if (StringUtils.isNotBlank(bookIdStr)) {
            Integer bookId = Integer.parseInt(bookIdStr);
            queryWrapper.eq("book_id", bookId);
        }

        // 用户ID筛选
        String userIdStr = (String) params.get("userId");
        if (StringUtils.isNotBlank(userIdStr)) {
            Integer userId = Integer.parseInt(userIdStr);
            queryWrapper.eq("user_id", userId);
        }

        // 状态筛选
        String statusStr = (String) params.get("status");
        if (StringUtils.isNotBlank(statusStr)) {
            Integer status = Integer.parseInt(statusStr);
            queryWrapper.eq("status", status);
        }

        // 评分筛选
        String ratingStr = (String) params.get("rating");
        if (StringUtils.isNotBlank(ratingStr)) {
            Integer rating = Integer.parseInt(ratingStr);
            queryWrapper.eq("rating", rating);
        }

        // 内容搜索
        String content = (String) params.get("content");
        if (StringUtils.isNotBlank(content)) {
            queryWrapper.like("content", content);
        }

        // 按创建时间倒序
        queryWrapper.orderByDesc("created_at");

        // 查询评论分页数据
        IPage<BookReview> reviewPage = this.page(new Page<>(current, size), queryWrapper);

        // 转换为ReviewVO
        IPage<ReviewVO> reviewVOPage = new Page<>(current, size, reviewPage.getTotal());
        List<ReviewVO> reviewVOList = reviewPage.getRecords().stream().map(review -> {
            ReviewVO reviewVO = new ReviewVO();
            BeanUtils.copyProperties(review, reviewVO);

            // 获取图书信息
            Book book = bookService.getById(review.getBookId());
            if (book != null) {
                reviewVO.setBookTitle(book.getTitle());
                reviewVO.setBookCover(book.getCover());
            }

            // 获取用户信息
            User user = userService.getById(review.getUserId());
            if (user != null) {
                reviewVO.setUserName(user.getUsername());
                reviewVO.setUserAvatar(user.getAvatar());
            }

            // 获取当前用户的点赞状态
            try {
                Long currentUserId = userContextUtil.getCurrentUserId();
                if (currentUserId != null) {
                    int likeCount = reviewLikeMapper.checkUserLiked(review.getId(), currentUserId.intValue());
                    reviewVO.setIsLiked(likeCount > 0);
                } else {
                    reviewVO.setIsLiked(false);
                }
            } catch (Exception e) {
                reviewVO.setIsLiked(false);
            }

            return reviewVO;
        }).collect(Collectors.toList());

        reviewVOPage.setRecords(reviewVOList);
        return reviewVOPage;
    }

    @Override
    public Map<String, Object> getReviewDetail(Integer reviewId) {
        BookReview review = this.getById(reviewId);
        if (review == null) {
            return null;
        }
        
        // 获取图书信息
        Book book = bookService.getById(review.getBookId());
        
        // 获取用户信息
        User user = userService.getById(review.getUserId());
        
        Map<String, Object> result = new HashMap<>();
        result.put("review", review);
        result.put("book", book);
        result.put("user", user);
        
        return result;
    }

    @Override
    public boolean deleteReview(Integer reviewId) {
        return this.removeById(reviewId);
    }

    @Override
    @Transactional
    public boolean toggleReviewStatus(Integer reviewId, Integer status) {
        // 先获取评论信息
        BookReview originalReview = this.getById(reviewId);

        BookReview review = new BookReview();
        review.setId(reviewId);
        review.setStatus(status);
        boolean result = this.updateById(review);

        if (result && originalReview != null && originalReview.getBookId() != null) {
            // 更新书籍的评论数
            updateBookReviewCount(originalReview.getBookId());
        }

        return result;
    }

    @Override
    public boolean updateReview(Integer reviewId, Map<String, Object> reviewData) {
        try {
            // 获取原评论信息
            BookReview originalReview = this.getById(reviewId);
            if (originalReview == null) {
                return false;
            }

            // 更新评论信息
            BookReview review = new BookReview();
            review.setId(reviewId);

            if (reviewData.containsKey("content")) {
                review.setContent((String) reviewData.get("content"));
            }
            if (reviewData.containsKey("rating")) {
                review.setRating((Integer) reviewData.get("rating"));
            }
            if (reviewData.containsKey("status")) {
                review.setStatus((Integer) reviewData.get("status"));
            }

            boolean reviewUpdated = this.updateById(review);

            // 如果包含封面信息，更新关联图书的封面
            if (reviewData.containsKey("bookCover") && reviewUpdated) {
                String newCover = (String) reviewData.get("bookCover");
                if (newCover != null && !newCover.isEmpty()) {
                    Book book = new Book();
                    book.setId(originalReview.getBookId());
                    book.setCover(newCover);
                    bookService.updateById(book);
                }
            }

            return reviewUpdated;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean batchDeleteReviews(List<Integer> reviewIds) {
        return this.removeByIds(reviewIds);
    }

    @Override
    @Transactional
    public boolean toggleReviewLike(Integer reviewId, Integer userId) {
        try {
            int likeCount = reviewLikeMapper.checkUserLiked(reviewId, userId);

            if (likeCount > 0) {
                // 取消点赞
                QueryWrapper<ReviewLike> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("review_id", reviewId).eq("user_id", userId);
                reviewLikeMapper.delete(queryWrapper);
            } else {
                // 添加点赞
                ReviewLike reviewLike = new ReviewLike();
                reviewLike.setReviewId(reviewId);
                reviewLike.setUserId(userId);
                reviewLikeMapper.insert(reviewLike);
            }

            // 更新点赞数
            int newLikeCount = reviewLikeMapper.getReviewLikeCount(reviewId);
            BookReview review = new BookReview();
            review.setId(reviewId);
            review.setLikes(newLikeCount);
            this.updateById(review);

            return true;
        } catch (Exception e) {
            log.error("点赞操作失败", e);
            return false;
        }
    }

}
